package com.gensdai.leliang.fragment;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.GridLayoutHelper;
import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.alibaba.android.vlayout.layout.SingleLayoutHelper;
import com.classic.common.MultipleStatusView;
import com.gensdai.leliang.R;
import com.gensdai.leliang.activity.ActivityBrand;
import com.gensdai.leliang.activity.OfflineStoreInfoActivity;
import com.gensdai.leliang.activity.OfflineStoreListActivity;
import com.gensdai.leliang.activity.ProductDetail;
import com.gensdai.leliang.activity.SearchActivity;
import com.gensdai.leliang.activity.UserNews;
import com.gensdai.leliang.activity.user_enter;
import com.gensdai.leliang.base.BaseFragment;
import com.gensdai.leliang.common.adapter.BannerAdapterRec;
import com.gensdai.leliang.common.adapter.ContentHotBigPicAdapterRec;
import com.gensdai.leliang.common.adapter.ContentTitleAdapterRec;
import com.gensdai.leliang.common.adapter.FootAdapterRec;
import com.gensdai.leliang.common.adapter.HotBrandAdapterRec;
import com.gensdai.leliang.common.adapter.HotOfflineAdapterRec;
import com.gensdai.leliang.common.adapter.HotProductAdapterRec;
import com.gensdai.leliang.common.adapter.HotProductYouLikeAdapterRec;
import com.gensdai.leliang.common.adapter.MainMenuViewPagerAdapterRec;
import com.gensdai.leliang.common.bean.BannerInfo;
import com.gensdai.leliang.common.bean.CategoryBean;
import com.gensdai.leliang.common.bean.TitleBean;
import com.gensdai.leliang.common.clickinterface.MenuItemChangeListener;
import com.gensdai.leliang.common.clickinterface.OnProductClickListener;
import com.gensdai.leliang.entity.HomeBean;
import com.gensdai.leliang.entity.User;
import com.gensdai.leliang.entity.parseBean.BaseParse;
import com.gensdai.leliang.entity.parseBean.ProductInfo;
import com.gensdai.leliang.json_base.json_base;
import com.gensdai.leliang.remoteInterface.ApiService;
import com.gensdai.leliang.remoteInterface.RetrofitFactory;
import com.gensdai.leliang.retrofitUtils.BaseObserver;
import com.gensdai.leliang.retrofitUtils.ModelFilteredFactory;
import com.gensdai.leliang.retrofitUtils.exception.APIException;
import com.gensdai.leliang.utils.BaseUtils;
import com.gensdai.leliang.view.Toaster;
import com.gensdai.leliang.view.banner.PageInfo;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import retrofit2.HttpException;

/**
 * Created by zsxx on 2017/6/15.
 */

public class FragmentRecyclerHome extends BaseFragment {

    @BindView(R.id.rcv_list)
    RecyclerView recyclerView;
    @BindView(R.id.geshu)
    TextView geshu;
    Unbinder unbinder;

    DelegateAdapter delegateAdapter;
    List<DelegateAdapter.Adapter> adapters;


    int marginTitle;
    int paddingLoR;

    @BindView(R.id.main_multiplestatusview)
    MultipleStatusView mainMultiplestatusview;


    /*
    线下体验店
    Intent it = new Intent(getActivity(), OfflineStoreListActivity.class);
                startActivity(it);
    */
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_recycler_home, container, false);
        unbinder = ButterKnife.bind(this, v);
        return v;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        marginTitle = getResources().getDimensionPixelOffset(R.dimen.px14dp);
        paddingLoR = getResources().getDimensionPixelOffset(R.dimen.px30dp);
        //创建线性布局
        final VirtualLayoutManager layoutManager = new VirtualLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        // layoutManager.setReverseLayout(true);

        RecyclerView.ItemDecoration itemDecoration = new RecyclerView.ItemDecoration() {
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int position = ((VirtualLayoutManager.LayoutParams) view.getLayoutParams()).getViewPosition();
                outRect.set(4, 4, 4, 4);
            }
        };

        final RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();

        recyclerView.setRecycledViewPool(viewPool);

        // recyclerView.addItemDecoration(itemDecoration);
        viewPool.setMaxRecycledViews(0, 20);

        delegateAdapter = new DelegateAdapter(layoutManager, false);

        recyclerView.setAdapter(delegateAdapter);

        adapters = new LinkedList<>();


    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        share = getActivity().getSharedPreferences("User", getActivity().MODE_PRIVATE);
        //设置重试视图点击事件
        mainMultiplestatusview.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getHomeRetro();
            }
        });
//        getHomeRetro();
//        getHome();
        getHomeRetro();

    }

    @Override
    public void onResume() {
        super.onResume();
        Query();
    }


    /**
     * 获取用户消息
     */
    private void getUserNewsCall() {

        String s = getActivity().getSharedPreferences("User", getActivity().MODE_PRIVATE).getString("newsCall", "0");
        if (Integer.parseInt(s) > 0) {
            geshu.setText(s);
            geshu.setVisibility(View.VISIBLE);
        }
//
    }

    SharedPreferences share;

    @OnClick(R.id.messagebox)
    public void onMessageClick(View v) {
        if (share.getBoolean("enter_state", false)) {
            Intent go_usercenter = new Intent(getActivity(), UserNews.class);
            startActivity(go_usercenter);
        } else {

            startActivity(new Intent(getActivity(), user_enter.class));
        }
    }

    @OnClick(R.id.search)
    public void onSearchClick(View v) {
        startActivity(new Intent(getActivity(), SearchActivity.class));
    }

//    private void getHome() {
//
//        if (!BaseUtils.isNetworkAvailable(getActivity())) {
//            //没有网络显示无网络
//            mainMultiplestatusview.showNoNetwork();
//            return;
//        }
//
//
//        ApiService.getInstance(getActivity()).getHome()
//                //涉及到IO操作
//                .subscribeOn(Schedulers.io())
//                .compose(this.<BaseParse<HomeBean>>bindUntilEvent(FragmentEvent.DESTROY)) //跟生命周期绑定一起
//                .doOnSubscribe(new Consumer<Disposable>() {
//                    @Override
//                    public void accept(@NonNull Disposable disposable) throws Exception {
//                        //开始监听前的处理，一般用于显示dialog什么的
//////                        if (hud != null) {
//////                            hud.show();
//////                        }
//                        //显示加载中视图
//                        mainMultiplestatusview.showLoading();
//                        Log.d("accept", "accept");
//                    }
//                })
//                .subscribeOn(AndroidSchedulers.mainThread())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Observer<BaseParse<HomeBean>>() {
//                    @Override
//                    public void onSubscribe(@NonNull Disposable d) {
//                        //可以取消订阅
//                        //还可以判断是否处于取消状态
//                        //boolean b=d.isDisposed();
//
//                        Log.d("onSubscribe", "onSubscribe");
//                    }
//
//                    @Override
//                    public void onNext(@NonNull BaseParse<HomeBean> s) {
//                        //处理得到的数据
////                        mainMultiplestatusview.showContent();
//                        Log.e("onNext", "s");
//                        changeView(s);
//
//                    }
//
//                    @Override
//                    public void onError(@NonNull Throwable e) {
//                        //异常处理
//                        e.printStackTrace();
//                        mainMultiplestatusview.showError();
//                        if (e instanceof APIException) {
//                            APIException exception = (APIException) e;
//                            Toast.makeText(getActivity(), exception.message, Toast.LENGTH_SHORT).show();
//                        } else if (e instanceof UnknownHostException) {
//                            Toast.makeText(getActivity(), "请打开网络", Toast.LENGTH_SHORT).show();
//                        } else if (e instanceof SocketTimeoutException) {
//                            Toast.makeText(getActivity(), "请求超时", Toast.LENGTH_SHORT).show();
//                        } else if (e instanceof ConnectException) {
//                            Toast.makeText(getActivity(), "连接失败", Toast.LENGTH_SHORT).show();
//                        } else if (e instanceof HttpException) {
//                            Toast.makeText(getActivity(), "请求异常" + ((HttpException) e).code(), Toast.LENGTH_SHORT).show();
//                        } else {
//                            Toast.makeText(getActivity(), "请求失败", Toast.LENGTH_SHORT).show();
//                        }
//                    }
//
//                    @Override
//                    public void onComplete() {
//                        //监听完毕后的处理
//                    }
//                });
//    }

//    private void changeView(BaseParse<HomeBean> homeBean) {
//        if (adapters != null) {
//            adapters.clear();
//        }
//        initViewPager(homeBean.data.bannerPic);//初始化banner
//        initMenu();        //初始化menu 菜单
//        TitleBean remai = new TitleBean("热卖推荐", R.mipmap.main_hoticon, ContextCompat.getColor(getActivity(), R.color.main_hottext_color), false);
//        inittitle(remai);
//        initHotShop(homeBean.data.hotProduct);  //初始化Hotshop热卖
//        TitleBean pinpai = new TitleBean("品牌热榜", R.mipmap.main_hotbrandicon, ContextCompat.getColor(getActivity(), R.color.main_hotbrandtext_color), false);
//        inittitle(pinpai);
//        initHotBrand(homeBean.data.brandList);
//        TitleBean xianxia = new TitleBean("线下体验服务馆", R.mipmap.main_offlinestore, ContextCompat.getColor(getActivity(), R.color.main_offlinestore_color), false);
//        inittitle(xianxia);
//        initOfflineStore(homeBean.data.tiyanShop);  //线下体验店
//        TitleBean cainixihuan = new TitleBean("猜你喜欢", R.mipmap.main_youlike, ContextCompat.getColor(getActivity(), R.color.main_youlike_color), false);
//        inittitle(cainixihuan);
//        initProductList(homeBean.data.youLikeProduct);  //初始化猜你喜欢的列表
//        initfoot();
//        //初始化完毕后开始适配
//        delegateAdapter.setAdapters(adapters);
////        delegateAdapter.notifyDataSetChanged();
//
//        //延迟3秒后显示内容页面
//        mainMultiplestatusview.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                mainMultiplestatusview.showContent();
//            }
//        }, 1000);
//    }


    //添加首页的子标题
    private void inittitle(TitleBean bean) {
        if (adapters != null) {
            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
            layoutHelper.setMargin(0, marginTitle, 0, 0);
            layoutHelper.setBgColor(ContextCompat.getColor(getActivity(), R.color.bgColor_new));
            ContentTitleAdapterRec bannerAdapter = new ContentTitleAdapterRec(getActivity(), layoutHelper, bean);
            bannerAdapter.setOnMoreClickListener(new ContentTitleAdapterRec.OnMoreClickListener() {
                @Override
                public void onMoreClickListener(int type) {
                    if (type == TitleBean.TYPYE_OFFLINESTORE) {
                        //去先下体验店的列表
                        startActivity(new Intent(getActivity(), OfflineStoreListActivity.class));
                    }
                }
            });
            adapters.add(bannerAdapter);
        }
    }

    //添加list foot
    private void initfoot() {
        if (adapters != null) {
            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
            layoutHelper.setPadding(0, 10, 0, 10);
            layoutHelper.setBgColor(ContextCompat.getColor(getActivity(), R.color.bgColor_new));
            FootAdapterRec bannerAdapter = new FootAdapterRec(getActivity(), layoutHelper);
            adapters.add(bannerAdapter);
        }
    }

    //初始化banner
    private void initViewPager(List<HomeBean.BannerPicBean> bannerPicBean) {
        List<PageInfo> infos = new ArrayList<>();
        for (HomeBean.BannerPicBean picBean : bannerPicBean) {
            PageInfo pageInfo = new PageInfo();
            pageInfo.setImgPath(picBean.logo);
            infos.add(pageInfo);
        }

        BannerInfo binfos = new BannerInfo();
        binfos.setInfos(infos);

        if (adapters != null) {
            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
            BannerAdapterRec bannerAdapter = new BannerAdapterRec(getActivity(), layoutHelper, binfos);
            bannerAdapter.setOnBannerItemClick(new BannerAdapterRec.OnBannerItemClick() {
                @Override
                public void OnItemClick(int position, PageInfo info) {
                    if (menulistener != null) {
                        menulistener.changePosition(ContentTypeFragment.HOT_0);
                    }
                }
            });
            adapters.add(bannerAdapter);
        }

    }


    //初始化menu菜单
    private void initMenu(List<CategoryBean> beans) {
//        List<MainMenu> menu = new ArrayList<>();
//        MainMenu baobao = new MainMenu();
//        baobao.setResId(R.mipmap.menu_baobao);
//        baobao.setName(getString(R.string.home_yuntong));
//
//
//        MainMenu wanju = new MainMenu();
//        wanju.setResId(R.mipmap.menu_wanju);
//        wanju.setName(getString(R.string.home_nongchanp));
//
//        MainMenu yingtong = new MainMenu();
//        yingtong.setResId(R.mipmap.menu_yingtong);
//        yingtong.setName(getString(R.string.home_yizhiwanju));
//
//
//        MainMenu lema = new MainMenu();
//        lema.setResId(R.mipmap.menu_lema);
//        lema.setName(getString(R.string.home_riyongpn));
//
//        MainMenu nongchanp = new MainMenu();
//        nongchanp.setResId(R.mipmap.menu_nongchanpin);
//        nongchanp.setName(getString(R.string.home_meizhuang));
//
//        MainMenu riyongp = new MainMenu();
//        riyongp.setResId(R.mipmap.menu_riyongp);
//        riyongp.setName(getString(R.string.home_hufu));
//
//        menu.add(baobao);
//        menu.add(wanju);
//        menu.add(yingtong);
//        menu.add(lema);
//        menu.add(nongchanp);
//        menu.add(riyongp);


        SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
        MainMenuViewPagerAdapterRec menu = new MainMenuViewPagerAdapterRec(getActivity(), layoutHelper, beans);
        menu.setOnMenuClick(new MainMenuViewPagerAdapterRec.OnMenuClickLis() {
            @Override
            public void OnMenuClick(Object menu) {
                if (menulistener != null) {
                    menulistener.changePosition((int) menu);
                }
            }
        });
        if (adapters != null) {
            adapters.add(menu);
        }


//        GridLayoutHelper layoutHelper = new GridLayoutHelper(3);
//        layoutHelper.setMargin(0, 0, 0, 0);
//        layoutHelper.setBgColor(ContextCompat.getColor(getActivity(), R.color.bgColor_new));
//
////        layoutHelper.setPadding(getResources().getDimensionPixelOffset(R.dimen.px34dp),getResources().getDimensionPixelOffset(R.dimen.px24dp),getResources().getDimensionPixelOffset(R.dimen.px34dp),getResources().getDimensionPixelOffset(R.dimen.px24dp));
//        layoutHelper.setPadding(0,getResources().getDimensionPixelOffset(R.dimen.px24dp),0,getResources().getDimensionPixelOffset(R.dimen.px24dp));
//        //横间距
//        layoutHelper.setHGap(0);
//        //垂直间距
//        layoutHelper.setVGap(getResources().getDimensionPixelOffset(R.dimen.px20dp));
//        if (adapters != null) {
//            MainMenuAdapterRec menuAdapter = new MainMenuAdapterRec(getActivity(), layoutHelper, beans);
//            menuAdapter.setOnMenuTypeClick(new MainMenuAdapterRec.MenuTypeOnclickListener<CategoryBean>() {
//                @Override
//                public void OnPositionClick(CategoryBean menu, int position) {
//                    if (menulistener != null) {
//                        menulistener.changePosition(menu.categoryNo);
//                    }
//                }
//            });
//            adapters.add(menuAdapter);
//        }

    }


    //初始化热卖推荐
    private void initHotShop(List<ProductInfo> list) {


        if (list != null && list.size() > 0) {
            final ProductInfo info = list.get(0);
            if (adapters != null) {
                SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
                layoutHelper.setBgColor(ContextCompat.getColor(getActivity(), R.color.bgColor_new));
                ContentHotBigPicAdapterRec bannerAdapter = new ContentHotBigPicAdapterRec(getActivity(), layoutHelper, info);
                bannerAdapter.setOnProductClicklistener(productClickListener);
                adapters.add(bannerAdapter);
            }
        }


        List<ProductInfo> plist = new ArrayList<>();
        for (int i = 1; i < list.size(); i++) {
            plist.add(list.get(i));
        }

        GridLayoutHelper layoutHelper = new GridLayoutHelper(3);
        layoutHelper.setPadding(paddingLoR, 0, paddingLoR, 0);
        layoutHelper.setMargin(0, 2, 0, 0);
        layoutHelper.setBgColor(ContextCompat.getColor(getActivity(), R.color.bgColor_new));
        //横间距
        layoutHelper.setHGap(getResources().getDimensionPixelOffset(R.dimen.px10dp));
        if (adapters != null) {
            HotProductAdapterRec menuAdapter = new HotProductAdapterRec(getActivity(), layoutHelper, plist);
            menuAdapter.setOnProductClicklistener(productClickListener);
            adapters.add(menuAdapter);
        }
    }

    OnProductClickListener productClickListener = new OnProductClickListener<ProductInfo>() {
        @Override
        public void OnProductClick(ProductInfo info, int position) {
            startPorductInfo(info.getId());
        }
    };


    //品牌热榜列表
    private void initHotBrand(List<HomeBean.BrandBean> list) {
        GridLayoutHelper layoutHelper = new GridLayoutHelper(4);
        layoutHelper.setPadding(paddingLoR, 0, paddingLoR, marginTitle);
        layoutHelper.setMargin(0, getResources().getDimensionPixelOffset(R.dimen.px0dp), 0, 0);
        layoutHelper.setBgColor(ContextCompat.getColor(getActivity(), R.color.bgColor_new));
        layoutHelper.setAutoExpand(false);
        //横间距
        layoutHelper.setHGap(getResources().getDimensionPixelOffset(R.dimen.px10dp));
        layoutHelper.setVGap(getResources().getDimensionPixelOffset(R.dimen.px10dp));

        List<HomeBean.BrandBean> beans;

        if (list.size() > 8) {
            beans = list.subList(0, 8);
        } else {
            beans = list;
        }

        if (adapters != null) {
            HotBrandAdapterRec menuAdapter = new HotBrandAdapterRec(getActivity(), layoutHelper, beans);
            menuAdapter.setOnItemClick(new HotBrandAdapterRec.OnHomeBrandItemClick() {
                @Override
                public void OnItemClick(HomeBean.BrandBean id) {
                    Intent it = new Intent(getActivity(), ActivityBrand.class);
                    it.putExtra(ActivityBrand.EXTRA_BRAND_ID, id);
                    startActivity(it);
                }
            });
            adapters.add(menuAdapter);
        }
    }

    //线下体验店热榜
    private void initOfflineStore(List<HomeBean.TiyanShopBean> list) {
        LinearLayoutHelper layoutHelper = new LinearLayoutHelper();
        layoutHelper.setDividerHeight(10);
        layoutHelper.setBgColor(ContextCompat.getColor(getActivity(), R.color.bgColor_new));
        if (adapters != null) {
            HotOfflineAdapterRec menuAdapter = new HotOfflineAdapterRec(getActivity(), layoutHelper, list);
            menuAdapter.setOnOfflineStoreItemclickListener(new HotOfflineAdapterRec.onOfflineStoreItemClick() {
                @Override
                public void onItemClick(String id) {
                    Intent it = new Intent(getActivity(), OfflineStoreInfoActivity.class);
                    it.putExtra(OfflineStoreInfoActivity.EXTRA_SID, id);
                    startActivity(it);

                }
            });
            adapters.add(menuAdapter);
        }
    }

    //初始化猜你喜欢的产品列表
    private void initProductList(List<ProductInfo> list) {
        GridLayoutHelper layoutHelper = new GridLayoutHelper(2);
        layoutHelper.setPadding(paddingLoR, 0, paddingLoR, marginTitle);
        layoutHelper.setBgColor(ContextCompat.getColor(getActivity(), R.color.bgColor_new));
        //横间距
        layoutHelper.setHGap(getResources().getDimensionPixelOffset(R.dimen.px10dp));
        layoutHelper.setVGap(getResources().getDimensionPixelOffset(R.dimen.px10dp));
        if (adapters != null) {
            HotProductYouLikeAdapterRec menuAdapter = new HotProductYouLikeAdapterRec(getActivity(), layoutHelper, list);
            menuAdapter.setOnProductClicklistener(productClickListener);
            adapters.add(menuAdapter);
        }
    }

    public MenuItemChangeListener menulistener;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (!(activity instanceof MenuItemChangeListener)) {
            //activity要实现此接口不然点击不跳转
        } else {
            menulistener = (MenuItemChangeListener) activity;
        }
    }


    //跳转到产品详情页面
    private void startPorductInfo(String pid) {
        Intent it = new Intent(getActivity(), ProductDetail.class);
        it.putExtra(ProductDetail.EXTRA_PID, pid/*"0063ed7e81b64fec8e0aa88212987639"*/);
        startActivity(it);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    /**
     * 查询消息
     */
    private void Query() {
        //获取edit的值后请求

        Map<String, String> loginParams = new HashMap<>();
        loginParams.put("userNo", getActivity().getSharedPreferences("User", getActivity().MODE_PRIVATE).getString("userno", ""));
        toStrNews(loginParams);
    }

    //返回字符串类型
    private void toStrNews(Map<String, String> loginParams) {
        ApiService.getInstance(getActivity()).CQUERY_MESSAGE_COUNT_Receipt(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<String>bindUntilEvent(FragmentEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        try {
                            int i = 0;
                            if (new json_base().GOOD(s)) {
                                String[] list = (String[]) new json_base().JsonCall(new JSONObject(s));
                                i = Integer.parseInt(list[0]) + Integer.parseInt(list[1]);
                                if (i > 0) {
                                    if (i > 99) {
                                        geshu.setText("99+");
                                    } else {
                                        geshu.setText(i + "");
                                    }
                                    geshu.setVisibility(View.VISIBLE);
                                } else {
                                    geshu.setVisibility(View.INVISIBLE);
                                }
                            } else {
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }


    private void getHomeRetro() {
        if (!BaseUtils.isNetworkAvailable(getActivity())) {
            //没有网络显示无网络
            mainMultiplestatusview.showNoNetwork();
            return;
        }
        Map<String, String> loginParams = new HashMap<>();
        loginParams.put("userNo", share.getString("userno", ""));
        ModelFilteredFactory
                .compose(RetrofitFactory.getInstance().API().getHome(loginParams)) //跟生命周期绑定一起)
                .compose(this.<BaseParse<HomeBean>>bindUntilEvent(FragmentEvent.DESTROY))
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //启动监听前的处理，一般用于显示dialog什么的
                        mainMultiplestatusview.showLoading();
                        Log.d("accept", "accept");
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<HomeBean>(getActivity()) {

                    @Override
                    public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
                        //监听  用d判断是否注册  会优先执行
                        super.onSubscribe(d);
                        Log.d("OnDisposable", "OnDisposable");
                    }

                    @Override
                    public void onHandleSuccess(HomeBean homeBean) {
                        //正确请求到数据 且success为true
                        changeView(homeBean);
                    }

                    @Override
                    public void onHandleError(int code, String message) {
                        //正确请求到数据 但是success为false
                        Toaster.showOneToast(code + ":" + message);
                    }

                    @Override
                    public void onFailure(final Throwable e) {
                        super.onFailure(e);
                        if (e instanceof APIException) {
                            APIException exception = (APIException) e;
                            Toast.makeText(getActivity(), exception.message, Toast.LENGTH_SHORT).show();
                        } else if (e instanceof UnknownHostException) {
                            Toast.makeText(getActivity(), "请打开网络", Toast.LENGTH_SHORT).show();
                        } else if (e instanceof SocketTimeoutException) {
                            Toast.makeText(getActivity(), "请求超时", Toast.LENGTH_SHORT).show();
                        } else if (e instanceof ConnectException) {
                            Toast.makeText(getActivity(), "连接失败", Toast.LENGTH_SHORT).show();
                        } else if (e instanceof HttpException) {
                            Toast.makeText(getActivity(), "请求异常" + ((HttpException) e).code(), Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getActivity(), "请求失败", Toast.LENGTH_SHORT).show();
                        }
                        mainMultiplestatusview.showError();
//                        mainMultiplestatusview.post(new Runnable() {
//                            @Override
//                            public void run() {
//
//                            }
//                        });
                    }

                });
    }

    private void changeView(HomeBean homeBean) {
        if (adapters != null) {
            adapters.clear();
        }
        if (homeBean.bannerPic != null)
            initViewPager(homeBean.bannerPic);//初始化banner
        if (homeBean.categoryList != null)
            initMenu(homeBean.categoryList);        //初始化menu 菜单
        TitleBean remai = new TitleBean("热卖推荐", R.mipmap.main_hoticon, ContextCompat.getColor(getActivity(), R.color.baseColor), false);
        inittitle(remai);
        if (homeBean.hotProduct != null)
            initHotShop(homeBean.hotProduct);  //初始化Hotshop热卖
        TitleBean pinpai = new TitleBean("品牌热榜", R.mipmap.main_hotbrandicon, ContextCompat.getColor(getActivity(), R.color.baseColor), false);
        inittitle(pinpai);
        if (homeBean.brandList != null)
            initHotBrand(homeBean.brandList);
        TitleBean xianxia = new TitleBean("线下体验", R.mipmap.main_offlinestore, ContextCompat.getColor(getActivity(), R.color.baseColor), TitleBean.TYPYE_OFFLINESTORE, true);
        inittitle(xianxia);
        if (homeBean.tiyanShop != null)
            initOfflineStore(homeBean.tiyanShop);  //线下体验店
        TitleBean cainixihuan = new TitleBean("猜你喜欢", R.mipmap.main_youlike, ContextCompat.getColor(getActivity(), R.color.baseColor), false);
        inittitle(cainixihuan);
        if (homeBean.youLikeProduct != null)
            initProductList(homeBean.youLikeProduct);  //初始化猜你喜欢的列表
        initfoot();
        //初始化完毕后开始适配
        delegateAdapter.setAdapters(adapters);
//        delegateAdapter.notifyDataSetChanged();

        //延迟3秒后显示内容页面
        mainMultiplestatusview.postDelayed(new Runnable() {
            @Override
            public void run() {
                mainMultiplestatusview.showContent();
            }
        }, 1000);
    }
}
